import { SearchPanel } from './screen-panel'
import { List } from './list'
import React, { useState, useEffect } from 'react'
import { objectToUrl } from 'utils'

const apiUrl = process.env.REACT_APP_API_URL

export const ProjectListScreen = () => {

  const [param, setParam] = useState({
    name: '',
    personId: ''
  })

  const [users, setUsers] = useState([])
  const debounceParam = useDebounce(param, 300)
  const [list, setList] = useState([])

  useEffect(() => {
    fetch(`${apiUrl}/projects${objectToUrl(param)}`).then(async response => {
      if (response.ok) {
        setList(await response.json())
      }
    })
  }, [debounceParam]) // eslint-disable-line react-hooks/exhaustive-deps

  useMount(() => {
    fetch(`${apiUrl}/users`).then(async response => {
      setUsers(await response.json())
    })
  })

  return <div>
    <SearchPanel users={users} param={param} setParam={setParam} />
    <List users={users} list={list} />
    <button></button>
  </div>
}


export const useMount = (callback:()=>void) => {
  useEffect(() => {
    callback()
  }, []) // eslint-disable-line react-hooks/exhaustive-deps
}

export const useDebounce = (value:string, delay:number) => {
  const [debounceValue, setDebounceValue] = useState(value)
  useEffect(() => {
    const timeout = setTimeout(() => setDebounceValue(value), delay)
    return () => clearTimeout(timeout)
  }, [value, delay])
  return debounceValue
}

export const useArray: <T>(initData: T) => { add: (item: T) => void, value: boolean } = (initData) => {
  const [value, setValue] = useState(initData)
  return {
    value,
    setValue,
    clear: () => setValue([]),
    add: (item) => setValue([...value, item]),
    removeIndex: (index:number) => {
      const copy = [...value]
      copy.splice(index, 1)
      setValue(copy)
    } 
  } 
}
